package com.welike.shibo.service.impl;

import com.welike.shibo.service.UploadService;
import com.welike.shibo.utils.QiNiuUtil;
import com.welike.shibo.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2019/12/30 9:49 上午
 */

@Slf4j
@Service(value = "uploadServiceImpl")
public class UploadServiceImpl implements UploadService {


    @Resource
    private QiNiuUtil qiNiuUtil;

    // 上传文件
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        try {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String fileExtend = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            //默认不指定key的情况下，以当前日期+时间戳作为文件名
            String key = Tools.getYearMonth() + System.currentTimeMillis() + fileExtend;

            return qiNiuUtil.uploadQiNiu(inputStream, key);
        }catch (Exception e){
            e.printStackTrace();
            return "上传失败";
        }
    }
}
